package com.jiumi.baseconfig.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.jiumi.common.utils.DateUtils;
import com.jiumi.common.utils.StringUtils;
import com.jiumi.util.TreeSelect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jiumi.baseconfig.mapper.BaseCategoryMapper;
import com.jiumi.baseconfig.domain.BaseCategory;
import com.jiumi.baseconfig.service.IBaseCategoryService;

/**
 * 栏目信息Service业务层处理
 *
 * @author jiumi
 * @date 2023-05-21
 */
@Service
public class BaseCategoryServiceImpl implements IBaseCategoryService
{
    @Autowired
    private BaseCategoryMapper baseCategoryMapper;

    /**
     * 查询栏目信息
     *
     * @param id 栏目信息主键
     * @return 栏目信息
     */
    @Override
    public BaseCategory selectBaseCategoryById(Long id)
    {
        return baseCategoryMapper.selectBaseCategoryById(id);
    }

    /**
     * 查询栏目信息列表
     *
     * @param baseCategory 栏目信息
     * @return 栏目信息
     */
    @Override
    public List<BaseCategory> selectBaseCategoryList(BaseCategory baseCategory)
    {
        return baseCategoryMapper.selectBaseCategoryList(baseCategory);
    }

    /**
     * 新增栏目信息
     *
     * @param category 栏目信息
     * @return 结果
     */
    @Override
    public int insertBaseCategory(BaseCategory category)
    {
        category.setCreateTime(DateUtils.getNowDate());

        Long parentId = category.getParentId();
        if (null != parentId) {
            BaseCategory info = baseCategoryMapper.selectBaseCategoryById(parentId);
            if (null != info) {
                category.setAncestors(info.getAncestors() + "," + category.getParentId());
            }
        }
        if(StringUtils.isNotEmpty(category.getAncestors())){
            String[] split = category.getAncestors().split(",");
            category.setLevel(split.length);
        }
        return baseCategoryMapper.insertBaseCategory(category);
    }

    /**
     * 修改栏目信息
     *
     * @param category 栏目信息
     * @return 结果
     */
    @Override
    public int updateBaseCategory(BaseCategory category)
    {
        BaseCategory newParent = baseCategoryMapper.selectBaseCategoryById(category.getParentId());
        BaseCategory oldInfo = baseCategoryMapper.selectBaseCategoryById(category.getId());
        if (StringUtils.isNotNull(newParent) && StringUtils.isNotNull(oldInfo)) {
            String newAncestors = newParent.getAncestors() + "," + newParent.getId();
            String oldAncestors = oldInfo.getAncestors();
            category.setAncestors(newAncestors);
            if(StringUtils.isNotEmpty(newAncestors)){
                String[] split = newAncestors.split(",");
                category.setLevel(split.length);
            }
            updateCategoryChildren(category.getId(), newAncestors, oldAncestors);
        }
        category.setUpdateTime(DateUtils.getNowDate());


        return baseCategoryMapper.updateBaseCategory(category);
    }

    private void updateCategoryChildren(Long id, String newAncestors, String oldAncestors) {
        List<BaseCategory> children = baseCategoryMapper.selectChildrenCategoryById(id);
        for (BaseCategory child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            baseCategoryMapper.updateCategoryChildren(children);
        }
    }

    /**
     * 批量删除栏目信息
     *
     * @param ids 需要删除的栏目信息主键
     * @return 结果
     */
    @Override
    public int deleteBaseCategoryByIds(Long[] ids)
    {
        return baseCategoryMapper.deleteBaseCategoryByIds(ids);
    }

    /**
     * 删除栏目信息信息
     *
     * @param id 栏目信息主键
     * @return 结果
     */
    @Override
    public int deleteBaseCategoryById(Long id)
    {
        return baseCategoryMapper.deleteBaseCategoryById(id);
    }



    @Override
    public List<TreeSelect> selectCategoryTreeList(BaseCategory category) {
        List<BaseCategory> categories = baseCategoryMapper.selectBaseCategoryList(category);
        return buildCategoryTreeSelect(categories);
    }

    private List<TreeSelect> buildCategoryTreeSelect(List<BaseCategory> categories) {
        List<BaseCategory> categoryTrees = buildCategoryTree(categories);
        return categoryTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    private List<BaseCategory> buildCategoryTree(List<BaseCategory> categories) {
        List<BaseCategory> returnList = new ArrayList<BaseCategory>();
        List<Long> tempList = categories.stream().map(BaseCategory::getId).collect(Collectors.toList());
        for (BaseCategory cate : categories) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(cate.getParentId())) {
                recursionFn(categories, cate);
                returnList.add(cate);
            }
        }
        if (returnList.isEmpty()) {
            returnList = categories;
        }
        return returnList;
    }

    private void recursionFn(List<BaseCategory> list, BaseCategory t) {
        // 得到子节点列表
        List<BaseCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (BaseCategory tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<BaseCategory> getChildList(List<BaseCategory> list, BaseCategory t) {
        List<BaseCategory> tlist = new ArrayList<BaseCategory>();
        Iterator<BaseCategory> it = list.iterator();
        while (it.hasNext()) {
            BaseCategory n = (BaseCategory) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<BaseCategory> list, BaseCategory t) {
        return getChildList(list, t).size() > 0;
    }

}
